package org.zch.common.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.lionsoul.ip2region.xdb.Searcher;
import org.zch.entity.vo.AddressVO;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * IP地址工具类
 *
 * @Author 刘新
 * @Date 2024/1/15 10:43
 */
public class IpUtils {

    /**
     * 获取国家
     *
     * @param ip
     * @return
     */
    public static String getCountry(String ip) {
        AddressVO vo = localIpQuery(ip);
        String country = vo.getCountry();
        return country;
    }

    /**
     * 获取省
     *
     * @param ip
     * @return
     */
    public static String getProvince(String ip) {
        AddressVO vo = baiduIp(ip);
        String province = vo.getProvince();
        return province;
    }

    /**
     * 获取市
     *
     * @param ip
     * @return
     */
    public static String getCity(String ip) {
        AddressVO vo = localIpQuery(ip);
        String city = vo.getCity();
        return city;
    }

    /**
     * 获取区
     *
     * @param ip
     * @return
     */
    public static String getDistrict(String ip) {
        AddressVO vo = localIpQuery(ip);
        String district = vo.getDistrict();
        return district;
    }

    /**
     * 离线ip查询（国省市区等数据均有）
     */
    public static AddressVO localIpQuery(String ip) {
        // 1、创建 searcher 对象
        // 备注：并发使用，每个线程需要创建一个独立的 searcher 对象单独使用。
        String dbPath = "src/main/resources/ip2region.xdb";
        Searcher searcher = null;
        try {
            searcher = Searcher.newWithFileOnly(dbPath);
        } catch (IOException e) {
            System.out.printf("failed to create searcher with `%s`: %s\n", dbPath, e);
            return new AddressVO();
        }

        // 2、查询
        String region = "";
        try {
            long sTime = System.nanoTime();
            region = searcher.search(ip);
            long cost = TimeUnit.NANOSECONDS.toMicros((long) (System.nanoTime() - sTime));
            System.out.printf("{region: %s, ioCount: %d, took: %d μs}\n", region, searcher.getIOCount(), cost);
            // 3、关闭资源
            searcher.close();
        } catch (Exception e) {
            System.out.printf("failed to search(%s): %s\n", ip, e);
        }
        // 解析返回值
        String[] arr = region.split("\\|");
        AddressVO vo = new AddressVO();
        vo.setCountry(arr[0]);
        vo.setProvince(arr[2]);
        vo.setCity(arr[3]);
        vo.setDistrict(arr[4]);
        return vo;
    }

    /**
     * 在线ip查询(只有省、市)
     */
    public static AddressVO onlineIp(String ip) {
        // 在线查询ip1
        String url = "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=" + ip;
        HttpUtils httpUtils = new HttpUtils();
        String result = httpUtils.doGet(url);
        JSONObject dataObj = JSONUtil.parseObj(result);
        // 组装统一返回数据
        AddressVO vo = new AddressVO();
        vo.setProvince(dataObj.getStr("pro"));
        vo.setCity(dataObj.getStr("city"));
        return vo;
    }


    /**
     * 百度在线ip查询（有国、省、市、区）
     */
    public static AddressVO baiduIp(String ip) {
        String url = "https://qifu.baidu.com/ip/geo/v1/district?ip=" + ip;
        // 在线查询ip1
        HttpUtils httpUtils = new HttpUtils();
        String result = httpUtils.doGet(url);
        JSONObject dataObj = JSONUtil.parseObj(result);
        // 组装统一返回数据
        AddressVO vo = new AddressVO();
        String dataStr = dataObj.getStr("data");
        JSONObject data = JSONUtil.parseObj(dataStr);
        vo.setCountry(data.getStr("country"));
        vo.setProvince(data.getStr("prov"));
        vo.setCity(data.getStr("city"));
        vo.setDistrict(data.getStr("district"));
        return vo;
    }

}
